using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemListManager : MonoBehaviour
{
    public float startPos;
    public float itemWith = 1080;

    public float disJudgeMax = .2f;
    public float disJudgeMin = .01f;

    public bool inLerping;

    public int maxIndex = 6;

    public int curIndex;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    private Vector3 m_OldPos;
    
    // Update is called once per frame
    void Update()
    {
        var vec = transform.localPosition - m_OldPos;
        float dis = vec.magnitude;
        if (dis > disJudgeMin && dis < disJudgeMax)
        {
            var localPos = transform.localPosition;
            var x = localPos.x;
            
            if (!inLerping)
            {
                inLerping = true;

                curIndex = (int)((x - startPos) / itemWith);
                
                if (vec.x < 0)
                {
                    float xdis = (x - startPos) - curIndex * itemWith;
                    if(Mathf.Abs(xdis) > Mathf.Abs(itemWith/2))
                        curIndex -= 1;
                }
                else
                {
                    float xdis = (x - startPos) - curIndex * itemWith;
                    if(Mathf.Abs(xdis) > Mathf.Abs(itemWith/2))
                        curIndex -= 1;
                }
            }

            float targetPos = startPos + curIndex * itemWith;

            float targetX = Mathf.Lerp(x, targetPos, .1f);
            
            var maxPos = startPos-this.maxIndex * itemWith;
            
            targetX = Mathf.Clamp(targetX, maxPos, startPos);
            //targetX = Mathf.Clamp(targetX, startPos,maxPos );
            
            localPos.x = targetX;
            
            transform.localPosition = localPos;
        }
        else
        {
            inLerping = false;
        }

        m_OldPos = transform.localPosition;
    }
}
